﻿using System;
using System.ComponentModel.Composition;
using System.Linq;
using Caliburn.Micro;
using Scrabble.Model;

namespace Scrabble.ViewModels
{
    [Export(typeof(BoardViewModel)), PartCreationPolicy(CreationPolicy.NonShared)]
    public class BoardViewModel : PropertyChangedBase, IHandle<HotPlayingVectorChanged>
    {
        private readonly Board _board;
        private readonly string[] _labelsAcross;
        private readonly string[] _labelsDown;
        private readonly Square[] _squares;

        private IInputBox _inputBox;
        private object _highlightCue;

        public BoardViewModel(Board board)
        {
            _board = board;
            _board.BoardChanged += (sender, args) => NotifyOfPropertyChange(() => TilesInPlay);

            _labelsAcross = Enumerable.Range('A', Board.Columns).Select(n => new String((char) n, 1)).ToArray();
            _labelsDown = Enumerable.Range(1, Board.Rows).Select(n => n.ToString()).ToArray();
            _squares = Board.AllSquares.Select(square => new Square(this, square.Item1, square.Item2)).ToArray();

            IoC.Get<IEventAggregator>().Subscribe(this);
        }

        public IInputBox InputBox
        {
            get { return _inputBox; }
            set
            {
                if (value == InputBox) return;

                _inputBox = value;
                NotifyOfPropertyChange(() => InputBox);
            }
        }

        public object LabelsAcross
        {
            get { return _labelsAcross; }
        }

        public object LabelsDown
        {
            get { return _labelsDown; }
        }

        public object Squares
        {
            get { return _squares; }
        }

        public object TilesInPlay
        {
            get { return _board.Tiles; }
        }

        public void SetStartOfPlayLocation(BoardLocation startingLocation)
        {
            if (InputBox != null) InputBox.AnchorLocation = startingLocation;
        }

        public object HighlightVector
        {
            get { return _highlightCue; }
            set
            {
                if (value == HighlightVector) return;

                _highlightCue = value;
                NotifyOfPropertyChange(() => HighlightVector);
            }
        }

        public void Handle(HotPlayingVectorChanged message)
        {
            HighlightVector = message.TargetVector;
        }
    }
}